/*
 * ============================================================================
 *
 *       Filename:  equipment.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  01/23/2018 02:32:40 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
/* XXX: uthash */
#include "logger.h"
#include "common.h"
#include "equipment.h"

equipment_t *equipmentlist = NULL;

equipment_t *add_equipment(equipment_t *eq)
{
	equipment_t *s = NULL;
	HASH_FIND(hh, equipmentlist, &(eq->username), strlen(eq->username), s);
	if(s == NULL) {
		HASH_ADD(hh, equipmentlist, username, strlen(eq->username), eq);
		s = eq;
	}

	return s;
}

void del_equipment(equipment_t *eq)
{
	equipment_t *s = NULL;
	HASH_FIND(hh, equipmentlist, &(eq->username), strlen(eq->username), s);
	if(s) {
		assert( s == eq);
		HASH_DEL(equipmentlist, eq);
		free(eq);
	}
}

equipment_t *find_equipment(const char * const username)
{
	equipment_t *s = NULL;
	HASH_FIND(hh, equipmentlist, username, strlen(username), s);
	return s;
}

equipment_t *find_equipment_raw(const char * const username, char *password)
{
	equipment_t *s = NULL;
	HASH_FIND(hh, equipmentlist, username, strlen(username), s);
	if(s) {
		if(strcmp(password, s->password) != 0) {
			logger_error("username: '%s', password: '%s' shoud be '%s' error\n",
				username, password, s->password);
			s = NULL;
		}
	}
	return s;
}

int equipment_unbind(const char * const username, char *password)
{
	equipment_t *eq;

	eq = find_equipment(username);
	if(!eq) {
		logger_error("unbind equipment error: %s %s\n",
			username, password);
		return -1;
	}
	if(strcmp(password, eq->password) != 0) {
		logger_error("unbind equipment error: %s %s\n",
			username, password);
		return -1;
	}

	logger_debug("unbind equipment: %s %s\n", username, password);
	del_equipment(eq);
	return 0;
}

int equipment_bind(const char *const username, char *password)
{
	equipment_t *eq;
	printf("bind equipment: %s %s\n", username, password);
	eq = find_equipment(username);
	if(!eq) {
		printf("create new equipment\n");
		eq = ss_malloc(sizeof(equipment_t));
		strcpy(eq->username, username);
		strcpy(eq->password, password);
		add_equipment(eq);
		return 0;
	}
	return -1;
}
